package codeTop;

public class q148 {
    public ListNode sortList(ListNode head) {
        return mergeSort(head);
    }
    ListNode mergeSort(ListNode node){
        if (node == null || node.next == null) {
            return node;
        }
        ListNode mid = findMid(node);
        ListNode midNext = mid.next;
        mid.next = null;
        ListNode left = mergeSort(node);
        ListNode right = mergeSort(midNext);
        ListNode merge = merge(left, right);
        return merge;
    }
    ListNode findMid(ListNode node){
        ListNode pre = new ListNode();
        pre.next = node;
        ListNode fast = pre;
        ListNode slow = pre;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    ListNode merge(ListNode node1,ListNode node2){
        ListNode head = new ListNode();
        ListNode p = head;
        while (node1 != null && node2 != null) {
            if (node1.val <= node2.val) {
                p.next = node1;
                node1 = node1.next;
            }else {
                p.next = node2;
                node2 = node2.next;
            }
            p = p.next;
        }
        if (node1 != null) {
            p.next = node1;
        }else {
            p.next = node2;
        }
        return head.next;
    }

    public static void main(String[] args) {
        q148 q = new q148();
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(1);
        ListNode node4 = new ListNode(3);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        q.sortList(node1);
    }
}
